var app = getApp();
// pages/cart/cart.js
Page({
  data: {
    page: 1,
    minusStatuses: ['disabled', 'disabled', 'normal', 'normal', 'disabled'],
    total: 0,
    carts: [],  
    contractName: null,
    baseUrl: app.d.ceshiUrl,
  },

  bindMinus: function(e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.carts[index].count;
    var cart_id = e.currentTarget.dataset.cartid;
    if (num > 1) {
      num--;
      e = {
        'cart_id': cart_id,
        'num': num,
        'index': index
      };
      that.updataNum(e);
    }
    console.log(num);


  },
  bindMinusPing: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var ping = that.data.carts[index].ping;
    var cart_id = e.currentTarget.dataset.cartid;
    if (ping > 0) {
      
      ping--;
      console.log(ping);
      var carts = that.data.carts;
      carts[index].ping = ping;

      that.setData({
        carts: carts,
      });
    }
    
  },

  bindManual: function(e) {
    console.log('bindManual')
    console.log(e)
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    // var num = that.data.carts[index].count;
    var num = e.detail.value;
    var cart_id = e.currentTarget.dataset.cartid;
    console.log(cart_id);
    console.log(num);
    console.log(index);
    e = {
      'cart_id': cart_id,
      'num': num,
      'index': index
    };
    that.updataNum(e);
  },
  bindManualPing: function (e) {
    console.log('bindManual')
    console.log(e)
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    
    var num = e.detail.value;
  
    var carts = that.data.carts;
    carts[index].ping = parseInt(num);

    that.setData({
      carts: carts,
    });

  },
 
  bindPlus: function(e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = that.data.carts[index].count;
    var ping = that.data.carts[index].ping;
    var pingtotal = that.data.carts[index].pingtotal;
    var cart_id = e.currentTarget.dataset.cartid;
    num++;
    console.log(pingtotal)
    console.log("pingtotal")
    console.log(num);
    if (pingtotal-num+ping<=0){
      wx.showToast({
        title: '可用瓶数已不够！',
        duration: 2000
      });
    }
    e = {
      'cart_id': cart_id,
      'num': num,
      'index': index
    };
    that.updataNum(e);

  },
  bindPlusping: function (e) {
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index);
    var ping = that.data.carts[index].ping;
    var cart_id = e.currentTarget.dataset.cartid;
    ping++;
    console.log(ping);
    var carts = that.data.carts;
    carts[index].ping = ping;
   
    that.setData({
      carts: carts,
    });

  },
  updataNum: function(e) {
    var that = this;
    var cart_id = e.cart_id;
    var num = e.num;
    var index = e.index;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/GoodsCartMgrAction!update',
      method: 'get',
      data: {
        'goodsCart.id': cart_id,
        'goodsCart.count': num,
      },
      header: app.globalData.header,
      success: function(res) {
        var status = res.data.success;
        console.log(res)
        if (status == 'true') {
          // 只有大于一件的时候，才能normal状态，否则disable状态
          var minusStatus = num <= 1 ? 'disabled' : 'normal';
          // 购物车数据
          var carts = that.data.carts;
          carts[index].count = num;
          // 按钮可用状态
          var minusStatuses = that.data.minusStatuses;
          minusStatuses[index] = minusStatus;
          that.setData({
            minusStatuses: minusStatuses
          });
          that.sum();
        } else {
          wx.showToast({
            title: '操作失败！',
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },


  bindCheckout: function() {
    var that = this;
    console.log(that.data.carts)

    let str = JSON.stringify(that.data.carts);
    wx.navigateTo({
      url: '../order/pay?carts=' + str,
    })
  },

  bindToastChange: function() {
    this.setData({
      toastHidden: true
    });
  },

  sum: function() {
    var that = this;
    var carts = this.data.carts;
    // 计算总金额
    var total = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].selected) {
        total += carts[i].count * carts[i].price;
        total = parseFloat(total.toFixed(2));
        console.log(total)
      }
    }
    // 写回经点击修改后的数组
    that.setData({
      carts: carts,
      total: total
    });
  },

  onLoad: function(options) {
    this.loadProductData();
    this.sum();
  },

  onShow: function() {
    this.loadProductData();
  },

  removeShopCard: function(e) {
    var that = this;
    var cardId = e.currentTarget.dataset.cartid;
    wx.showModal({
      title: '提示',
      content: '你确认移除吗',
      success: function(res) {
        res.confirm && wx.request({
          url: app.d.ceshiUrl + '/transaction/GoodsCartMgrAction!del',
          method: 'get',
          data: {
            'goodsCart.id': cardId,
          },

          header: app.globalData.header,
          success: function(res) {
            //--init data
            console.log(res)
            var data = res.data;
            if (data.success == 'true') {
              //that.data.productData.length =0;
              that.loadProductData();
            } else {
              wx.showToast({
                title: '操作失败！',
                duration: 2000
              });
            }
          },
        });
      },
      fail: function() {
        // fail
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    });
  },

  // 数据案例
  loadProductData: function() {

    var that = this;
    that.getCat();
    // console.log("app.globalData.header:" + app.globalData.header['Cookie']);
// 根据ID获取合同内容  好像没啥用，不能删
    // wx.request({
    //   url: app.d.ceshiUrl + '/transaction/ContractMgrAction!selectById?contractId=1',
    //   method: 'post',
    //   data: {},
    //   // header: {
    //   //   'content-type': 'application/json',
    //   // },
    //   header: app.globalData.header,
    //   success: function (res) {
    //     var obj1 = res.data.obj;
    //     console.log(res)
    //     that.getCat();
    //   },
    //   fail: function (e) {
    //     wx.showToast({
    //       title: '网络异常！',
    //       duration: 2000
    //     });
    //   },
    // })
  },

  getCat: function() {
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/transaction/StoreCartMgrAction!listGoods',
      method: 'post',

      header: app.globalData.header,
      success: function(res) {

        console.log(res)
        var cart = res.data.rows;
        var total = 0;
        console.log(cart)
        if (res.data.success == 'false') {
          cart=''
          console.log('false')
          that.setData({
            carts: [],
          });
        }
        if (cart=='') {
           that.setData({
            carts: [],
          });
          return 
        }else{
          
          for (var i = 0; i < cart.length; i++) {
            cart[i].selected = true;
            cart[i].ping = 0;
            cart[i].pingtotal = i+30;
            total += cart[i].count * cart[i].price;

          }
        }

        that.setData({
          contractName: res.data.contract_name,
          carts: cart,
          total: total
        });
        console.log(that.data.contractName);
       
      },
      fail: function(e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    });
  }

})